package com.chixing.day11.day11_Hom;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateTest {
    public static void main(String[] args) throws ParseException {
        //获得当前时间
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sf = new SimpleDateFormat("HH:mm:ss");
        System.out.println("当前时间: " + sf.format(cal.getTime()));

        //获得2天以后的日期
        Calendar cal2 = Calendar.getInstance();
        SimpleDateFormat sf2 = new SimpleDateFormat("yyyy-MM-dd");
        cal2.add(Calendar.DATE, 2);
        String date = sf2.format(cal2.getTime());
        System.out.println("2天以后的日期: " + date);

        // 获得3天前的日期
        Calendar cal3 = Calendar.getInstance();
        SimpleDateFormat sf3 = new SimpleDateFormat("yyyy-MM-dd");
        cal3.add(Calendar.DATE, -3);
        String date1 = sf3.format(cal3.getTime());
        System.out.println("3天前的日期: " + date1);

        // 将字符串"2022/7/21 19:30" 转换成日期对象
        SimpleDateFormat sf4 = new SimpleDateFormat("yyyy/MM/dd HH:mm");
        String dateArr = "2022/7/21 19:30";
        try {
           Date date2 = sf4.parse(dateArr);
            System.out.println("转换成日期对象: " + date2);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        // 比较两天日期对象date  相差的天数
        SimpleDateFormat sf5 = new SimpleDateFormat("yyyy-MM-dd");
        Date date3 = sf5.parse("2000-02-15");
        Date date4 = sf5.parse("2000-03-10");
        Calendar cal4 = Calendar.getInstance();
        cal4.setTime(date3);
        int day1 = cal4.get(Calendar.DAY_OF_YEAR);
        cal4.setTime(date4);
        int day2 = cal4.get(Calendar.DAY_OF_YEAR);
        int days = day2 - day1;
        System.out.println("相差的天数: " + days);
    }
}
